Re: [SQL] Counting the number of distinct rows returned

Поиск
Список
Период
Сортировка
От Herouth Maoz
Тема Re: [SQL] Counting the number of distinct rows returned
Дата
Msg-id l03130301b3e59de25f8a@[147.233.159.109]
обсуждение исходный текст
Ответ на Re: [SQL] Counting the number of distinct rows returned  ("Sejin Oh" <soh@cyberix.com>)
Список pgsql-sql
At 16:56 +0300 on 19/08/1999, Sejin Oh wrote:


> yeah... GROUP BY should do..
>
> try this:
>
> SELECT COUNT(*) FROM sales_by_region GROUP BY user_id;

No, no, it returns the exact opposite of what he wanted. Imagine a table
that has the values

fld
===
2
1
2
1
3

Doing select distinct on this table would return

fld
===
2
1
3

Therefore the number Drew needed is 3. But SELECT COUNT(*) with GROUP BY
would give:

fld  count
===  =====
2    2
1    2
3    1

That is, for each distinct value, it will give the frequency of that value
in the table. This is not the number of distinct values, it is the number
of times each distinct value appears.

I have once already posted a (kinda kludgy) solution for this in the
absence of COUNT DISTINCT in PostgreSQL:

SELECT count(*)
FROM the_table t1
WHERE int4( oid ) =
( SELECT max( int4(oid) ) FROM the_table t2 WHERE t1.fld = t2.fld );

The inner select gives you the maximal oid of the row that has a given
field value. The outer select selects only rows whose oid is this maximal
one. Thus it selects only one row for each distinct value, and so the count
is COUNT DISTINCT. If the original SELECT DISTINCT selected several fields,
more fields should be added to the WHERE clause of the subselect.

A more efficient solution would probably be:

SELECT DISTINCT( fld )
INTO TABLE tmp_tbl
FROM the_table;

SELECT COUNT( * ) -- This is the query that returns the needed result
FROM tmp_tbl;

DROP TABLE tmp_tbl;


Herouth

--
Herouth Maoz, Internet developer.
Open University of Israel - Telem project
http://telem.openu.ac.il/~herutma




В списке pgsql-sql по дате отправления:

Предыдущее
От: Eric Enockson
Дата:
Сообщение: can i send without being a member
Следующее
От: Herouth Maoz
Дата:
Сообщение: Re: [SQL] What JDBC datatype can be used for DATETIME ?